import axios from 'axios'
import { showToast, closeToast } from 'vant'

const baseURL = process.env.NODE_ENV === 'production' 
  ? 'https://api.dify.ai/v1'
  : '/dify'

// 创建axios实例
const service = axios.create({
  baseURL,
  timeout: 180000, // 延长到3分钟
  headers: {
    'Content-Type': 'application/json'
  },
  // 添加重试配置
  retry: 3,
  retryDelay: 1000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 确保重试配置存在
    config.retry = config.retry || 3
    config.retryDelay = config.retryDelay || 1000
    
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.config.responseType === 'blob') {
      return response
    }
    
    const res = response.data
    if (res.code && res.code !== 200) {
      showToast({
        message: res.message || '请求失败',
        type: 'fail',
        duration: 2000
      })
      
      if (res.code === 401) {
        localStorage.removeItem('token')
        setTimeout(() => {
          window.location.reload()
        }, 1500)
      }
      
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    
    return res
  },
  async error => {
    const { config } = error
    
    // 如果配置不存在，或重试次数用完，则不再重试
    if (!config || !config.retry) {
      let message = '网络错误，请稍后重试'
      if (error.response) {
        switch (error.response.status) {
          case 400:
            message = '请求错误'
            break
          case 401:
            message = '未授权，请登录'
            localStorage.removeItem('token')
            setTimeout(() => {
              window.location.reload()
            }, 1500)
            break
          case 403:
            message = '拒绝访问'
            break
          case 404:
            message = '请求地址不存在'
            break
          case 500:
            message = '服务器内部错误'
            break
          default:
            message = `请求失败: ${error.response.status}`
        }
      } else if (error.request) {
        message = '服务器无响应'
      } else if (error.code === 'ECONNABORTED') {
        message = '请求超时，请检查网络后重试'
      }
      
      showToast({
        message,
        type: 'fail',
        duration: 2000
      })
      
      return Promise.reject(error)
    }
    
    // 重试次数减1
    config.retry -= 1
    
    // 延时重试
    await new Promise(resolve => setTimeout(resolve, config.retryDelay))
    
    // 重新发起请求
    return service(config)
  }
)

// 封装 HTTP 方法
export const get = (url, params = {}) => {
  return service.get(url, { params })
}

export const post = (url, data = {}) => {
  return service.post(url, data)
}

export const put = (url, data = {}) => {
  return service.put(url, data)
}

export const del = (url) => {
  return service.delete(url)
}

export default service